package com.zhangxu.microservice.employee.web.config;

import com.zhangxu.microservice.common.context.EmployeeContextHolder;
import com.zhangxu.microservice.common.dto.EmployeeContextDTO;
import com.zhangxu.microservice.common.exception.BizException;
import com.zhangxu.microservice.common.utils.AssertUtils;
import com.zhangxu.microservice.employee.biz.service.EmployeeBizService;
import com.zhangxu.microservice.employee.domain.dto.EmployeeDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class AeLoginInterceptor implements HandlerInterceptor {

    private final EmployeeBizService userBizService;

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String employeeIdStr = request.getHeader("employeeId");
        try {
            AssertUtils.hasLength(employeeIdStr, "");
            Long employeeId = Long.parseLong(employeeIdStr);
            EmployeeDTO employeeDTO = userBizService.getById(employeeId);
            AssertUtils.notNull(employeeDTO, "获取用户授权信息失败");
            EmployeeContextDTO employeeContextDTO = new EmployeeContextDTO();
            employeeContextDTO.setId(employeeId);
            employeeContextDTO.setAccount(employeeDTO.getAccount());
            employeeContextDTO.setName(employeeDTO.getName());
            employeeContextDTO.setEmail(employeeDTO.getEmail());
            employeeContextDTO.setPhone(employeeDTO.getPhoneCrypto());
            EmployeeContextHolder.set(employeeContextDTO);
        } catch (Exception e) {
            // 可记录日志，但不抛异常避免影响业务
            throw new BizException("获取用户授权信息失败");
        }
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        EmployeeContextHolder.clear();
    }
}
